package com.sdk.springbootrediscache.rediscachemanager;


import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    private Map<Long, String> userMap = new HashMap<>();

    // 从缓存中获取用户信息，如果缓存中不存在，则执行方法并将结果存入缓存
    @Cacheable(value = "users", key = "#userId" )
    public String getUserById(Long userId) {
        System.out.println("Fetching user from database...");
        return userMap.get(userId);
    }

    // 更新用户信息，并更新缓存
    @CachePut(value = "users", key = "#userId")
    public String updateUser(Long userId, String userName) {
        userMap.put(userId, userName);
        return userName;
    }

    // 删除用户信息，并从缓存中移除
    @CacheEvict(value = "users", key = "#userId")
    public void deleteUser(Long userId) {
        userMap.remove(userId);
    }
}
